package com.fiberhome.nas.core.network.di

import android.content.Context
import android.net.wifi.WifiManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.InetSocketAddress
import java.net.Socket
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine


class NetworkManager(private val context: Context) {
    // 定义IP地址
    private val localIp = "192.168.100.1"
    private val remoteIp = "123.123.123.123"
    private val port = 8080
    private val timeout = 2000

    var baseUrl = "http://$localIp:$port"

    // 获取当前应该使用的baseUrl
    suspend fun getBaseUrl(): String {
        return withContext(Dispatchers.IO) {
            if (isWifiEnabled()) {
                // WiFi已打开，检查本地IP连通性
                if (isHostReachable(localIp, port, timeout)) {
                    "http://$localIp:$port"
                } else {
                    "http://$remoteIp:$port"
                }
            } else {
                // WiFi未打开，使用远端IP
                "http://$remoteIp:$port"
            }
        }
    }

    // 检查WiFi是否已启用
    private fun isWifiEnabled(): Boolean {
        val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        return wifiManager.isWifiEnabled
    }

    // 检查主机是否可达
    private suspend fun isHostReachable(host: String, port: Int, timeout: Int): Boolean {
        return suspendCoroutine {
            try {
                val socket = Socket()
                // 异步连接
                socket.connect(InetSocketAddress(host, port), timeout)
                socket.close()
                it.resume(true)
            } catch (e: Exception) {
                it.resume(false)
            }
        }
    }

}